﻿using BasicData.Domain;
using BasicData.ErrorCode;
using BasicData.Infastruucture;
using BasicData.Write.API.application.Command.Role;
using MediatR;

namespace BasicData.Write.API.application.CommandHandler.Role
{
    public class AddUserRoleCommandHandler : IRequestHandler<AddUserRoleCommand, ApiResult<object>>
    {

        private readonly IBaseRepository<UserRoleModel> useroleRepo;

        public AddUserRoleCommandHandler(IBaseRepository<UserRoleModel> useroleRepo)
        {
            this.useroleRepo = useroleRepo;
        }
        public Task<ApiResult<object>> Handle(AddUserRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> res = new ApiResult<object>();
            List<UserRoleModel> userolelist = useroleRepo.GetAll().Where(o => o.UserId == request.UserId).ToList();
            int a = 0, b = 0;
            if (userolelist != null)
            {
                foreach (UserRoleModel user in userolelist)
                {
                    user.IsDeleted = true;
                    a = useroleRepo.Update(user);
                }
            }
            string[] ids = request.RoleId.Split(',');
            foreach (string id in ids)
            {
                UserRoleModel userrole = new UserRoleModel();
                userrole.UserId = request.UserId;
                userrole.RoleId = Convert.ToInt32(id);
                b=useroleRepo.Create(userrole);
            }
            if (b > 0)
            {
                res.Code = BaseEnums.Success;
                res.Msg = "添加成功";
                res.Data = a;
            }
            else
            {
                res.Code = BaseEnums.Failed;
                res.Msg = "添加失败";
                res.Data = a;
            }
            return Task.FromResult(res);
        }
    }
}
